import time
from selenium import webdriver
import sys
import json

app_info = sys.argv[1:]
if app_info == '':
    pass
'''
[
{"appid":1336013705,"begin_time":1544079540,"end_time":1544111940,
    "keywords":[{"name":"\u6355\u9c7c\u6e38\u620f\u5385","plan_num":1000,"ranking":2},
                {"name":"\u7ecf\u5178\u6355\u9c7c","plan_num":2000,"ranking":3},
                {"name":"\u5343\u70ae\u6355\u9c7c","plan_num":3000,"ranking":4}]},
{"appid":1385559642,"begin_time":1544079540,"end_time":1544111940,"keywords":[{"name":"\u517b\u6210\u7c7b","plan_num":1500,"ranking":2}]},
{"appid":1261753872,"begin_time":1544079540,"end_time":1544111940,"keywords":[{"name":"\u5168\u519b\u7a81\u51fb","plan_num":1000,"ranking":2},{"name":"5v5\u7ade\u6280","plan_num":2000,"ranking":3},{"name":"\u90e8\u843d\u6218\u4e89","plan_num":3000,"ranking":4}]}]


'''
login_url = 'https://www.qimai.cn/account/signin/r/%2F'
#driver = webdriver.Chrome()

PROXY = "115.28.209.249:3128"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server={0}'.format(PROXY))
driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get(login_url)
# 检测是否有弹框
try:
    driver.find_element_by_css_selector('.close.iconfont.icon-shibai').click()
except:
    pass
# 填充登录表单
driver.find_element_by_name('username').send_keys('17621062647')
driver.find_element_by_name('password').send_keys('ldd1234')
driver.find_element_by_xpath('//span[text()="登录"]/..').click()
time.sleep(0.5)
# 自动跳转回首页后
for app in app_info:
    app_url = 'https://www.qimai.cn/app/keyword/appid/{}/country/cn'.format(app['appid'])
    driver.get(app_url)
    # 搜索关键词
    time.sleep(0.5)
    driver.find_element_by_xpath('//*[@id="app-keyword"]/div[2]/div[2]/div[1]/div[4]/div[1]/div[2]/ul/li[1]/div/input').send_keys("三国，qq,weixin")

    # 获取关键词排名数据
    time.sleep(2)
    tr_ele = driver.find_elements_by_xpath('//*[@id="app-keyword"]/div[2]/div[2]/div[2]/div[1]/div/div[2]/table/tbody/tr')
    for td in tr_ele:
        keyword = td.find_element_by_xpath('./td[1]/div/a').text
        rank = td.find_element_by_xpath('./td[2]/div/span').text
        print(keyword, rank)

driver.quit()